﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Core.Metadata;
using Luna.WPF.ApplicationFramework;
using XWord.Fundamental.Domain.Model;
using Microsoft.Practices.ServiceLocation;
using XWord.Fundamental.Domain;
using System.Threading;
using XWord.WPF.ApplicationFramework;
using XWord.GUI.Presenters.Interface;
using XWord.Fundamental.Domain.Services;
using System.Windows.Threading;
using XWord.WPF.ApplicationFramework.Threads;
using XWord.Common;
using System.Collections.Specialized;
using System.Windows;
using Caliburn.PresentationFramework.ApplicationModel;
using System.IO;

namespace XWord.GUI.Presenters.Fundamental
{
    [Singleton(typeof(AppendixTabPresenter))]
    public class AppendixTabPresenter : DockingPresenter, ITabPresenter
    {
        private readonly IServiceLocator _serviceLocator;

        public AppendixTabPresenter()
        {
            this.Index = 3;
            _serviceLocator = ServiceLocator.Current;
        }

        protected override void OnInitialize()
        {
            AppendixList = Appendix.GetAppendixList();
            base.OnInitialize();
        }

        private IList<Appendix> _appendixList;
        public IList<Appendix> AppendixList
        {
            get { return _appendixList ?? (_appendixList = new List<Appendix>()); }
            set
            {
                _appendixList = value;
                NotifyOfPropertyChange("AppendixList");
            }
        }

        private List<WebBrowserPresenter> _presenters = new List<WebBrowserPresenter>();

        public void OpenAppendix(object appendix)
        {
            if (appendix == null) return;

            var title = (appendix as Appendix).Title;
            if (_presenters.Any(e => e.DisplayName == title))
            {
                var currentPresenter = _presenters.First(e => e.DisplayName == title);
                _serviceLocator.GetInstance<IDockSitePresenter>().Activate(currentPresenter);
                return;
            }

            var presenter = _serviceLocator.GetInstance<WebBrowserPresenter>();
            _presenters.Add(presenter);
            presenter.WasShutdown += new EventHandler(presenter_WasShutdown);
            //index-zh-CN
            var zhCN = string.Format("{0}//{1}//index-zh-CN.html", Appendix.APPENDIXPATH, title);
            if (File.Exists(zhCN))
            {
                presenter.ShowLocal(title, zhCN);
            }
            else
                presenter.ShowLocal(title, string.Format("{0}//{1}//index.html", Appendix.APPENDIXPATH, title));
        }

        void presenter_WasShutdown(object sender, EventArgs e)
        {
            var presenter = sender as WebBrowserPresenter;
            presenter.WasShutdown -= presenter_WasShutdown;
            _presenters.Remove(presenter);
        }

        public int Index{get;set;}    
    }
}
